#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

#define FIFO_NAME "/tmp/watchDogfifo"
#define BUFFER_SIZE PIPE_BUF
#define TEN_MEG (1024 * 100)

static int pipe_fd;
static int res;

void initWatchDogWrite()
{

	    int bytes = 0;


	    if (access(FIFO_NAME, F_OK) == -1)
	    {
	        res = mkfifo(FIFO_NAME, 0777);
	        if (res != 0)
	        {
	            fprintf(stderr, "Could not create fifo %s\n", FIFO_NAME);
	            return;
	        }
	    }
	    printf("Process %d opening FIFO O_WRONLY\n", getpid());
	 	pipe_fd = open(FIFO_NAME, O_WRONLY);
	 	printf("Process %d result %d\n", getpid(), pipe_fd);
}


void initWatchDogRead()
{

	  int open_mode = O_RDONLY;
	     char buffer[BUFFER_SIZE + 1];
	     int bytes = 0;
	     int i=0;
	     memset(buffer, '\0', sizeof(buffer));
	    printf("Process %d opeining FIFO O_RDONLY\n", getpid());

	    for(i=0;i<10;i++)
	    {
	    	 pipe_fd = open(FIFO_NAME, open_mode);
	    	 if (pipe_fd != -1)
	         {
	    		 break;
	         }
	    	 else
	    	 {
	    		  printf("Process %d opeining FIFO O_RDONLY\n", getpid());
	    	      sleep(1);
	    	 }
	    }
	    if(i>=10)
	    {
	    	system("reboot");
	    }

}

void feedDog()
{
	 int bytes = 0;
	  char buffer[BUFFER_SIZE + 1];
	  res = write(pipe_fd, buffer, 1);
	  if (res == -1)
	  {
	                fprintf(stderr, "Write error on pipe\n");
	                exit(EXIT_FAILURE);
	  }

}


static int errCount=0;
void watch()
{
	char buffer[1024];
	  int bytes = 0;
	    int res;

	 while(1)
	 {

	     res = read(pipe_fd, buffer, BUFFER_SIZE);
	     if(res==0)
	     {
	    	 errCount++;
	    	 if(errCount>60*1) //
	    	 {
	    		 system("reboot");
	    	 }
	     }
	     else
	     {
	    	errCount=0;
	     }
	     sleep(1);
	 }

}
